from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, desc, func
from sqlalchemy.orm import relationship
from .base import Base, db
from app.spider.ys_book import YsBook


class Wish(Base):
    id = Column(Integer, primary_key=True)
    user = relationship('User')
    uid = Column(Integer, ForeignKey('user.id'))
    isbn = Column(String(15), nullable=False)
    # book = relationship('Book')
    # bid = Column(Integer, ForeignKey('user.id'))
    launched = Column(Boolean, default=False)

    @property
    def book(self):
        """
        心愿对应的书籍
        :return:
        """
        ys_book = YsBook()
        ys_book.search_by_isbn(self.isbn)
        return ys_book.first

    @classmethod
    def get_user_wishes(cls, uid):
        """
        用户的心愿清单
        :param uid:
        :return:
        """
        wishes = cls.query.filter_by(uid=uid, launched=False).order_by(desc(cls.create_time)).all()
        return wishes

    @classmethod
    def get_gift_count(cls, isbn_list):
        """
        书籍的赠送数量统计
        :param isbn_list:
        :return:
        """
        from .gift import Gift
        count_list = db.session.query(func.count(Gift.id), Gift.isbn).filter(
            Gift.launched == False, Gift.isbn.in_(isbn_list), Gift.status == 1
        ).group_by(Gift.isbn).all()
        # 转换成列表
        count_list = [{'count': w[0], 'isbn': w[1]} for w in count_list]
        return count_list
